<template>
	<view v-bind="$attrs" :class="['button-group', disabled ? 'button-group-disabled':'']">
		<button v-for="(button, index) in buttons" :key="index"
			:class="['button-item', selectedVal == button.value ? 'button-item-active' : '', selectedVal == button.value ? btSelectClass : btClass ]"
			@click="handleClick(button)" @longpress="longPress(button)" @touchend="touchEnd" @touchmove="touchMove">
			<image class="button-icon" mode="aspectFit" :src="button.icon" v-if="button.icon"></image>
			<text class="button-text">{{ button.label }}</text>
		</button>
		<button v-if="optText !=''" :class="['button-item', btClass] " @click="clickOpt">
			<text class="button-text"> {{optText}}</text>
		</button>
	</view>
</template>

<script setup>
	import {
		ref,
		watch
	} from 'vue';

	const props = defineProps({
		buttons: {
			type: Array,
			required: true,
			default: () => [],
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		modelValue: {
			type: null, // 任意类型
			default: null,
		},
		btClass: {
			type: String,
			default: '',
		},
		btSelectClass: {
			type: String,
			default: '',
		},
		optText: {
			type: String,
			default: ''
		}
	});

	const emit = defineEmits(['update:modelValue', 'click', 'longPress', 'clickOpt']);

	const selectedVal = ref(props.modelValue == null && props.buttons.length > 0 ? props.buttons[0].value : props
		.modelValue);

	// 监听 modelValue，buttons 的变化

	watch(
		[() => props.modelValue, () => props.buttons],
		([newModelValue, newButtons]) => {
			if (newModelValue == null) {
				if (newButtons.length > 0) {
					// 默认第一个
					selectedVal.value = newButtons[0].value
				}
			} else {
				selectedVal.value = newModelValue
			}
		}
	);

	let isLongPress = true
	/**
	 * 长按
	 */
	const longPress = (item) => {
		if (isLongPress) {
			emit('longPress', item);
		}
	}

	/**
	 * 结束触摸时，恢复可长按
	 */
	const touchEnd = () => {
		isLongPress = true;
	}

	/**
	 * 触摸移动时，禁止长按
	 */
	const touchMove = (e) => {
		isLongPress = false;
	}

	// 点击了选择
	const handleClick = (item) => {
		let value = item.value
		let oldValue = selectedVal.value
		if (oldValue == value) {
			return
		}
		selectedVal.value = value;
		emit('update:modelValue', value);
		emit('click', item);
	};

	// 点击了操作
	const clickOpt = () => {
		emit('clickOpt');
	}
</script>
<style scoped>
	.button-group {
		display: flex;
	}

	.button-group-disabled {
		pointer-events: none
	}

	.button-item {
		margin: 0;
		padding: 3rpx 20rpx 0;
		height: 60rpx;
		background-color: #eee;
		border-radius: 30rpx;
		border: none;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		gap: 10rpx;
	}

	.button-icon {
		height: 40rpx;
		width: 40rpx;
	}

	.button-text {
		font-size: 26rpx;
		color: #333;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.button-item-active {
		background-color: #07c160;
		color: #fff
	}
</style>